<template>
  <div class="roles-container">
   
    
    <el-card class="roles-card">
      <div class="page-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索角色名称"
          clearable
          @clear="handleSearch"
          style="width: 250px;"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
        
        <el-button type="primary" @click="handleAddRole">
          <el-icon><Plus /></el-icon>新增角色
        </el-button>
    </div>
      <el-table :data="filteredRoleList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="120" />
        <el-table-column prop="code" label="角色编码" width="120" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="'启用'"
              :inactive-value="'禁用'"
              @change="(val) => handleStatusChange(scope.row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleEditRole(scope.row)">编辑</el-button>
            <el-button size="small" type="success" link @click="handlePermission(scope.row)">权限</el-button>
            <el-button size="small" type="danger" link @click="handleDeleteRole(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRoles"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 角色表单对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" placeholder="请输入角色编码" :disabled="dialogType === 'edit'" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="4" placeholder="请输入角色描述" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="roleForm.status"
            :active-value="'启用'"
            :inactive-value="'禁用'"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRoleForm" :loading="submitLoading">确认</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 权限设置对话框 -->
    <el-dialog
      title="权限设置"
      v-model="permissionDialogVisible"
      width="600px"
    >
      <div v-if="currentRole.id" class="permission-header">
        <span class="role-name">角色：{{ currentRole.name }}</span>
      </div>
      
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTreeData"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedPermissions"
        :props="{ label: 'name', children: 'children' }"
      >
        <template #default="{ node, data }">
          <div class="permission-node">
            <el-icon v-if="data.type === 'menu'"><Menu /></el-icon>
            <el-icon v-else-if="data.type === 'button'"><Operation /></el-icon>
            <el-icon v-else><Folder /></el-icon>
            <span>{{ node.label }}</span>
          </div>
        </template>
      </el-tree>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermissions" :loading="permissionLoading">保存</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      title="删除确认"
      v-model="deleteDialogVisible"
      width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon" color="#ff4d4f" :size="24"><WarningFilled /></el-icon>
        <p>确定要删除角色 <strong>{{ currentRole.name }}</strong> 吗？此操作不可恢复！</p>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete" :loading="deleteLoading">确认删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Setting, Plus, Menu, Operation, Folder, WarningFilled } from '@element-plus/icons-vue'
import { getRoleList, createRole, updateRole, deleteRole, updateRoleStatus, getRolePermissions, updateRolePermissions, getPermissionTree } from '@/api/role'
import { Role, Permission, RoleForm } from '@/types/role'

// 状态变量
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalRoles = ref(0)
const searchKeyword = ref('')
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const submitLoading = ref(false)
const permissionDialogVisible = ref(false)
const permissionLoading = ref(false)
const deleteDialogVisible = ref(false)
const deleteLoading = ref(false)

// 表单引用
const roleFormRef = ref()
const permissionTreeRef = ref()

// 当前操作的角色
const currentRole = reactive<Role>({
  id: 0,
  name: '',
  code: '',
  description: '',
  createTime: '',
  status: '启用'
})

// 角色表单数据
const roleForm = reactive<RoleForm>({
  name: '',
  code: '',
  description: '',
  status: '启用'
})

// 表单校验规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

// 模拟角色数据
const roleList = ref<Role[]>([])

// 模拟权限树数据
const permissionTreeData = ref<Permission[]>([])

// 当前角色的权限ID列表
const checkedPermissions = ref<number[]>([])

// 根据搜索条件过滤角色列表
const filteredRoleList = computed(() => {
  if (!searchKeyword.value) {
    return roleList.value
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return roleList.value.filter(role => 
    role.name.toLowerCase().includes(keyword) || 
    role.code.toLowerCase().includes(keyword)
  )
})

// 加载角色数据
const loadData = () => {
  loading.value = true
  
  // 调用API获取角色列表
  getRoleList({
    page: currentPage.value,
    pageSize: pageSize.value,
    keyword: searchKeyword.value
  }).then(response => {
    roleList.value = response.data.list
    totalRoles.value = response.data.total
  }).catch(error => {
    console.error('获取角色列表失败', error)
    ElMessage.error('获取角色列表失败')
  }).finally(() => {
    loading.value = false
  })
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  loadData()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadData()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

// 处理角色状态变更
const handleStatusChange = (role: Role, status: string) => {
  updateRoleStatus(role.id, status).then(() => {
    ElMessage.success(`已${status}角色: ${role.name}`)
  }).catch(error => {
    console.error('更新角色状态失败', error)
    ElMessage.error('更新角色状态失败')
    // 恢复原来的状态
    role.status = role.status === '启用' ? '禁用' : '启用'
  })
}

// 重置表单
const resetRoleForm = () => {
  roleForm.id = undefined
  roleForm.name = ''
  roleForm.code = ''
  roleForm.description = ''
  roleForm.status = '启用'
  
  nextTick(() => {
    roleFormRef.value?.clearValidate()
  })
}

// 打开新增角色对话框
const handleAddRole = () => {
  dialogType.value = 'add'
  resetRoleForm()
  dialogVisible.value = true
}

// 打开编辑角色对话框
const handleEditRole = (role: Role) => {
  dialogType.value = 'edit'
  resetRoleForm()
  
  roleForm.id = role.id
  roleForm.name = role.name
  roleForm.code = role.code
  roleForm.description = role.description
  roleForm.status = role.status
  
  dialogVisible.value = true
}

// 打开权限设置对话框
const handlePermission = (role: Role) => {
  Object.assign(currentRole, role)
  
  // 获取权限树
  loadPermissionTree()
  
  // 获取角色的权限
  loadRolePermissions(role.id)
  
  permissionDialogVisible.value = true
}

// 加载权限树
const loadPermissionTree = () => {
  getPermissionTree().then(response => {
    permissionTreeData.value = response.data
  }).catch(error => {
    console.error('获取权限树失败', error)
    ElMessage.error('获取权限树失败')
  })
}

// 加载角色的权限
const loadRolePermissions = (roleId: number) => {
  getRolePermissions(roleId).then(response => {
    checkedPermissions.value = response.data
  }).catch(error => {
    console.error('获取角色权限失败', error)
    ElMessage.error('获取角色权限失败')
    
    // 回退到模拟数据（仅用于演示）
    if (roleId === 1) {
      checkedPermissions.value = [111, 112, 113, 114, 121, 122, 123, 124, 125, 131, 132, 133, 134, 211, 212, 213, 214, 221, 222, 223, 224, 31, 32]
    } else if (roleId === 2) {
      checkedPermissions.value = [111, 112, 113, 121, 122, 123, 131, 132, 133, 211, 212, 213, 221, 222, 223, 31, 32]
    } else if (roleId === 3) {
      checkedPermissions.value = [111, 211, 212, 213, 214, 221, 222, 223, 224, 31]
    } else if (roleId === 4) {
      checkedPermissions.value = [111, 121, 131, 211, 221, 31]
    } else {
      checkedPermissions.value = [111, 211, 221]
    }
  })
}

// 保存权限设置
const savePermissions = () => {
  permissionLoading.value = true
  
  // 获取选中的权限ID
  const selectedPermissions = permissionTreeRef.value.getCheckedKeys()
  
  // 调用API更新权限
  updateRolePermissions(currentRole.id, selectedPermissions).then(() => {
    ElMessage.success(`已成功更新角色 ${currentRole.name} 的权限设置`)
    permissionDialogVisible.value = false
  }).catch(error => {
    console.error('更新角色权限失败', error)
    ElMessage.error('更新角色权限失败')
  }).finally(() => {
    permissionLoading.value = false
  })
}

// 打开删除确认对话框
const handleDeleteRole = (role: Role) => {
  Object.assign(currentRole, role)
  deleteDialogVisible.value = true
}

// 确认删除角色
const confirmDelete = () => {
  deleteLoading.value = true
  
  // 调用API删除角色
  deleteRole(currentRole.id).then(() => {
    // 从列表中移除角色
    const index = roleList.value.findIndex(item => item.id === currentRole.id)
    if (index !== -1) {
      roleList.value.splice(index, 1)
    }
    
    ElMessage.success('删除成功')
    deleteDialogVisible.value = false
  }).catch(error => {
    console.error('删除角色失败', error)
    ElMessage.error('删除角色失败')
  }).finally(() => {
    deleteLoading.value = false
  })
}

// 提交角色表单
const submitRoleForm = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    
    submitLoading.value = true
    
    if (dialogType.value === 'add') {
      // 添加新角色
      createRole(roleForm).then(response => {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        // 重新加载数据
        loadData()
      }).catch(error => {
        console.error('添加角色失败', error)
        ElMessage.error('添加角色失败')
      }).finally(() => {
        submitLoading.value = false
      })
    } else {
      // 更新现有角色
      updateRole(roleForm.id!, roleForm).then(response => {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        // 更新本地数据
        const index = roleList.value.findIndex(item => item.id === roleForm.id)
        if (index !== -1) {
          roleList.value[index] = {
            ...roleList.value[index],
            name: roleForm.name,
            description: roleForm.description,
            status: roleForm.status
          }
        }
      }).catch(error => {
        console.error('更新角色失败', error)
        ElMessage.error('更新角色失败')
      }).finally(() => {
        submitLoading.value = false
      })
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

onMounted(() => {
  // 先加载模拟数据，等后端API就绪后可替换为loadData()
  // 模拟API调用
  loading.value = true
  
  // 示例数据，实际项目中使用loadData()从API获取
  setTimeout(() => {
    roleList.value = [
      {
        id: 1,
        name: '超级管理员',
        code: 'SUPER_ADMIN',
        description: '系统最高权限，可以操作所有功能',
        createTime: '2025-01-01 12:00:00',
        status: '启用'
      },
      {
        id: 2,
        name: '管理员',
        code: 'ADMIN',
        description: '系统管理员，可以操作大部分功能',
        createTime: '2025-01-02 10:30:00',
        status: '启用'
      },
      {
        id: 3,
        name: '编辑',
        code: 'EDITOR',
        description: '内容编辑，负责内容管理',
        createTime: '2025-01-03 15:20:00',
        status: '启用'
      },
      {
        id: 4,
        name: '普通用户',
        code: 'USER',
        description: '普通用户，基础功能访问权限',
        createTime: '2025-01-04 09:15:00',
        status: '启用'
      },
      {
        id: 5,
        name: '访客',
        code: 'GUEST',
        description: '访客角色，只读权限',
        createTime: '2025-01-05 14:40:00',
        status: '禁用'
      },
      {
        id: 6,
        name: '访客',
        code: 'GUEST',
        description: '访客角色，只读权限',
        createTime: '2025-01-05 14:40:00',
        status: '禁用'
      },
      {
        id: 7,
        name: '访客',
        code: 'GUEST',
        description: '访客角色，只读权限',
        createTime: '2025-01-05 14:40:00',
        status: '禁用'
      },
      {
        id: 8,
        name: '访客',
        code: 'GUEST',
        description: '访客角色，只读权限',
        createTime: '2025-01-05 14:40:00',
        status: '禁用'
      },
      {
        id: 9,
        name: '访客',
        code: 'GUEST',
        description: '访客角色，只读权限',
        createTime: '2025-01-05 14:40:00',
        status: '禁用'
      },
      {
        id: 10,
        name: '访客',
        code: 'GUEST',
        description: '访客角色，只读权限',
        createTime: '2025-01-05 14:40:00',
        status: '禁用'
      }
    ]
    
    permissionTreeData.value = [
      {
        id: 1,
        name: '系统管理',
        type: 'module',
        children: [
          {
            id: 11,
            name: '用户管理',
            type: 'menu',
            children: [
              { id: 111, name: '查看用户', type: 'button' },
              { id: 112, name: '新增用户', type: 'button' },
              { id: 113, name: '编辑用户', type: 'button' },
              { id: 114, name: '删除用户', type: 'button' }
            ]
          },
          {
            id: 12,
            name: '角色管理',
            type: 'menu',
            children: [
              { id: 121, name: '查看角色', type: 'button' },
              { id: 122, name: '新增角色', type: 'button' },
              { id: 123, name: '编辑角色', type: 'button' },
              { id: 124, name: '删除角色', type: 'button' },
              { id: 125, name: '分配权限', type: 'button' }
            ]
          },
          {
            id: 13,
            name: '权限管理',
            type: 'menu',
            children: [
              { id: 131, name: '查看权限', type: 'button' },
              { id: 132, name: '新增权限', type: 'button' },
              { id: 133, name: '编辑权限', type: 'button' },
              { id: 134, name: '删除权限', type: 'button' }
            ]
          }
        ]
      },
      {
        id: 2,
        name: '内容管理',
        type: 'module',
        children: [
          {
            id: 21,
            name: '文章管理',
            type: 'menu',
            children: [
              { id: 211, name: '查看文章', type: 'button' },
              { id: 212, name: '新增文章', type: 'button' },
              { id: 213, name: '编辑文章', type: 'button' },
              { id: 214, name: '删除文章', type: 'button' }
            ]
          },
          {
            id: 22,
            name: '分类管理',
            type: 'menu',
            children: [
              { id: 221, name: '查看分类', type: 'button' },
              { id: 222, name: '新增分类', type: 'button' },
              { id: 223, name: '编辑分类', type: 'button' },
              { id: 224, name: '删除分类', type: 'button' }
            ]
          }
        ]
      },
      {
        id: 3,
        name: '数据统计',
        type: 'module',
        children: [
          { id: 31, name: '访问统计', type: 'menu' },
          { id: 32, name: '用户统计', type: 'menu' }
        ]
      }
    ]
    
    totalRoles.value = roleList.value.length
    loading.value = false
  }, 500)
  
  // 实际项目中取消注释下面一行，并注释上面的模拟数据加载
  // loadData()
})
</script>

<style scoped>
.roles-container {
  padding: var(--content-padding);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  background-color: white;
  padding: 16px 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary, #303133);
}

.page-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.page-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  margin-bottom: 10px;
}

.roles-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.delete-confirm {
  display: flex;
  align-items: center;
  gap: 12px;
}

.warning-icon {
  font-size: 24px;
  color: #ff4d4f;
}

.permission-header {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.role-name {
  font-weight: bold;
  font-size: 16px;
}

.permission-node {
  display: flex;
  align-items: center;
  height: 100%;
}

.permission-node .el-icon {
  margin-right: 6px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .page-actions {
    width: 100%;
    flex-wrap: wrap;
  }
}
</style> 